package tools.Tree;


import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: Forx
 * @Data: 2021/6/22
 * @Desc: Algorithm - tools.Tree
 * @Version: v1.0
 */
public class Tree {
    public static Node strToTreeRecu(Queue queue){
        String value = (String) queue.poll();
        if("#".compareTo(value) == 0){
            return null;
        }
        Node head = new Node(Integer.valueOf(value));
        head.left = strToTreeRecu(queue);
        head.right = strToTreeRecu(queue);
        return head;

    }
    public static Node strToTree(String string){
        String[] values = string.split(" ");
        Queue<String> queue = new LinkedList<>();
        for(String str:values){
            queue.add(str);
        }
        return strToTreeRecu(queue);
    }
    public static void printTree(Node head) {
        System.out.println("Binary Tree:");
        printInOrder(head, 0, "H", 17);
        System.out.println();
    }

    public static void printInOrder(Node head, int height, String to, int len){
        if (head == null) {
            return;
        }
        printInOrder(head.right, height + 1, "v", len); // 递归遍历右子树
        String val = to + head.val + to; // 处理并打印根节点
        int lenM = val.length();
        int lenL = (len - lenM) / 2;
        int lenR = len - lenM - lenL;
        val = getSpace(lenL) + val + getSpace(lenR);
        System.out.println(getSpace(height * len) + val);
        printInOrder(head.left, height + 1, "^", len); // 递归遍历左子树
    }

    public static String getSpace(int num) {
        String space = " ";
        StringBuffer buf = new StringBuffer("");
        for (int i = 0; i < num; i++) {
            buf.append(space);
        }
        return buf.toString();
    }
}
